﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Famofo.Agbara.Core.FreeSwitch;
using System.Threading.Tasks;

namespace Famofo.Agbara.Sample.InboundSample
{
    public class Sample1: InboundSocket
    {
        const string EVENT_FILTER = "BACKGROUND_JOB API CHANNEL_EXECUTE_COMPLETE";
        public Sample1()
            : base("127.0.0.1", 8021, "ClueCon", EVENT_FILTER,  1000, false)
        {
        }
        public void start()
        {
            try
            {
                base.connect();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error Connecting with exception message {0}", ex.Message);
            }

            base.OnAPI += new EventHandlers(On_API);
            base.OnBACKGROUND_JOB += new EventHandlers(On_Background_Job);
            base.OnCHANNEL_EXECUTE_COMPLETE += new EventHandlers(on_channel_execute_complete);
        }
        
        private void On_Background_Job(Event evnt)
        {
            Console.WriteLine(string.Format("Received BackgrounJob {0} with JobUUID {1} ", evnt.EventName, evnt.get_header("Job-UUID")));
        }
        private void on_channel_execute_complete(Event ev)
        {
            Console.WriteLine(string.Format("application done {0}", ev.get_header("Application")));
        }
        
        private void On_API(Event evnt)
        {
            Console.WriteLine(string.Format("Received APIEvent {0} with Date {1}", evnt.EventName, evnt.EventDateLocal));
        }

        public static void InboundSocketSample()
        {
            Sample1 soc = new Sample1(); 
            Event bgapi1 = new Event();
            Event api1 = new Event();
            
            soc.start();
            string musicfile = "C:/sounds/music/8000/ponce-preludio-in-e-major.wav";
            string address = "127.0.0.1:8084";
            string dial_string = string.Format("origination_caller_id_number={0},originate_timeout={1}",234803820,30);
            string cmd = String.Format("originate [{0}]sofia/internal/{1}%{2} &playback({3})", dial_string, 1001, "127.0.0.1", musicfile);
            string socketcmd = String.Format("originate [{0}]sofia/internal/{1}%{2} 'socket:{3} async full' inline", dial_string, 1001, "127.0.0.1", address);
                bgapi1 = soc.bgapi(socketcmd);
                string jobUUId = BgApiResponse.Cast(bgapi1).GetJobUUID();
                Console.WriteLine("The job UUID is {0}", jobUUId);
                //api1 = soc.api(cmd);
                //Console.WriteLine("The API Result is {0}", api1.get_reply_text());

            soc.serve_forever();
        }
    }
}
